"""
运行server
"""
import subprocess
import sys

import flask

from app import routes
from app.database import init_db
from app.oauth_server import  config_oauth


def run_migrations():
    """执行 Alembic 数据库迁移"""
    try:
        # 检查是否需要升级
        result = subprocess.run(
            ["alembic", "current"],
            capture_output=True,
            text=True
        )
        if "head" not in result.stdout:
            print("正在执行数据库迁移...")
            subprocess.check_call(["alembic", "upgrade", "head"])
        else:
            print("数据库已是最新版本")
    except subprocess.CalledProcessError as e:
        sys.exit(f"数据库迁移失败: {str(e)}")


def create_app():
    """

    :return:
    """

    a = flask.Flask(__name__)

    a.config.from_object('app.config.Config')
    config_oauth(a)
    init_db(a)

    a.register_blueprint(routes.bp)

    return a


if __name__ == '__main__':
    run_migrations()
    app = create_app()
    app.run(port=8080)
